<?php

namespace app\web\controller;

use app\common\controller\Frontend;
use app\common\model\customer\Customer;
use app\common\model\customer\Customer as customerModel;
use app\common\model\data\Voucher;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\sales\CheckoutGoods;
use app\common\model\sales\Checkout as checkoutModel;
use app\common\model\sales\Goods;
use app\common\model\sales\Slip;
use think\Db;
use think\Exception;

class Checkout extends Frontend
{

    protected $noNeedLogin = '';
    protected $noNeedRight = 'index,getcheckout';
    protected $layout = '';

    public function add(){
        if ($this->request->isAjax()) {
            $ids = input('ids/d',0);
            $slip = new Slip;
            $row = $slip->find($ids);
            if(!$row){
                $this->error('没有对应销售单');
            }
            $customer = new Customer;
            $crow =  $customer->find($row['customer_id']);

            $params = input();

            if(!isset($params['datas'])){
                $this->error('没有出库的商品');
            }
            $gdata = $params['datas'];
            $sales_slip_id = $ids;
            $srow = $row;

            $num = Db::name('sales_checkout')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

            $allfare = input('allfare/d');
//            $discount = input('discount');
//            $discount_explain = input('discount_explain');
            $actual_cost = 0;
            $checkout_num = 0;

            foreach ($gdata as &$v){
                $info = Db::name('sales_goods')->where(array('id'=>$v['id']))->find();
                $v['goods_id'] = $info['goods_id'];
                $checkout_num+=$v['check_num'];
                $actual_cost += $info['ht_price']*$v['check_num'];
            }

            //添加出库单
            $data = array(
//                'createtime'=>strtotime(input('createtime')),
                'number'=>'XK-T-'.date('Y-m-d').'-'.getnumber($num),
                'customer_id'=>$row['customer_id'],
                'storehouse_id'=>$row['storehouse_id'],
//                'collectiontime'=>strtotime(input('deliverytime')),
                'address'=>empty($srow['address'])?$crow['address']:$srow['address'],
                'contacts'=>empty($srow['contacts'])?$crow['contacts']:$srow['contacts'],
                'mobile'=>empty($srow['mobile'])?$crow['mobile']:$srow['mobile'],
                'explain'=>input('explain'),
//                'abstract'=>input('abstract'),
                'sales_slip_id'=>$ids,
                'tax'=>$srow['tax'],
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'allfare'=>$allfare,
                'actual_cost'=>$actual_cost,
                'checkout_num'=>$checkout_num,
            );
            Db::startTrans();
            try {
                $model = new checkoutModel;
                $model->save($data);
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$row['storehouse_id'],
                    'bill_id'=>$model->id,
                    'type'=>7,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                //添加 入库商品信息
                //数据对比
                foreach ($gdata as $v) {
                    $goods = new Goods();
                    $ginfo = $goods->where(array('id'=>$v['id']))->find();

                    $GoodsHouseStock = new GoodsHouseStock;
                    $stock = $GoodsHouseStock->getstock($ginfo['goods_id'],$ginfo['storehouse_id']);
//                    $xstock = $GoodsHouseStock->getfictstock($ginfo['goods_id'],$ginfo['storehouse_id']);

                    if($stock-$v['goods_num']<0){
                        throw new Exception('商品' . $v['goods_id'] . '账面库存不足');
                    }
//                    if($xstock<0){
//                        throw new Exception('商品' . $v['goods_id'] . '虚拟库存不足');
//                    }

                    //剩余出库数量 = 销售数量-已出库数量
                    $EnterGoods = new CheckoutGoods;
                    $egoodcont = $EnterGoods->where(array('sales_slip_id' => $sales_slip_id, 'goods_id' => $v['goods_id'],'status'=>1))->sum('goods_num');

                    if ($v['check_num'] > $ginfo['goods_num'] - $egoodcont) {
                        throw new Exception('商品' . $v['goods_id'] . '数量超过销售数量,目前出库' . $egoodcont);
                    } else {//粗糙记录商品状态
                        $Goods = new Goods;
                        $Goods->save(array('status'=>2),array('sales_slip_id'=>$sales_slip_id,'status'=>1));
                    }
                    $gods = new \app\common\model\goods\Goods();
                    $costPrice = $gods->getcost($v['goods_id'],$row['storehouse_id']);
                    //存储记录
                    $cgdata[] = array(
                        'sales_slip_id' => $sales_slip_id,
                        'costPrice' => $costPrice,
                        'storehouse_id' => $row['storehouse_id'],
                        'goods_id' => $ginfo['goods_id'],
                        'goods_num' => $v['check_num'],
                        'sale_price' => $ginfo['sale_price'],
                        'tax' => $ginfo['tax'],
//                        'remark' => $v['remark'],
                        'ht_price' => $ginfo['ht_price'],
                        'sales_checkout_id' => $model->id,
                        'customer_id' => $row['customer_id'],
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'createtime'=>time(),
                    );


                }

                $CheckoutGoods = new CheckoutGoods;
                $CheckoutGoods->saveAll($cgdata);
                //判断销售单是否完成
                $gnum = Db::name('sales_goods')->where(array('sales_slip_id' => $sales_slip_id,'status'=>array('<',5)))->sum('goods_num');
                $goods = new CheckoutGoods();
                $succnum = $goods->where(array('sales_slip_id' => $sales_slip_id,'status'=>array('>=',1)))->sum('goods_num');

                if ($gnum == $succnum) {
                    $Slip = new Slip;
                    $Slip->save(array('status' => 4), array('id' => $sales_slip_id));
                } else {
                    $Slip = new Slip;
                    $Slip->save(array('status' => 3), array('id' => $sales_slip_id));
                }
                Db::commit();
                return array(
                    'code' => 1,
                    'msg' => '添加成功'
                );
            }catch (\Exception $e) {
//                dump($e);
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->error('非法操作');
    }
    public function index(){
        $model = new checkoutModel;
        $status = $model->checkout_status();
//        $where['storehouse_id'] = session('admin')['storehouse_id'];
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];
        $where['storehouse_id'] = $storehouse_id;

        $list = Db::name('sales_checkout')
            ->field('s.id,s.number,explain,s.operator,s.company,checkout_num,actual_cost,h.name,c.company as ccompany,s.status')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->limit(0,10)
            ->where($where)
            ->order('s.id','DESC')
            ->select();
        $total = Db::name('sales_checkout')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->where($where)
            ->count();
        foreach ($list as &$v){
            $v['status_txt'] = $status[$v['status']];
        }
        $this->assign('total',$total);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function getcheckout(){

        $page = input('page/d',1);
        $status = input('status/d',0);
        $pagesize = input('pagesize/d',10);
        $where = [];
//        $where['storehouse_id'] = session('admin')['storehouse_id'];
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];
        $where['storehouse_id'] = $storehouse_id;
        if($status){
           $where['s.status'] = $status;
        }

        $model = new checkoutModel;
        $status = $model->checkout_status();
        $list = Db::name('sales_checkout')
            ->field('s.id,s.number,explain,s.operator,s.company,checkout_num,actual_cost,h.name,c.company as ccompany,s.status')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->limit($page*$pagesize,$pagesize)
            ->where($where)
            ->order('s.id','DESC')
            ->select();
//        $total = Db::name('sales_slip')
//            ->alias('s')
//            ->join('storehouse h','s.storehouse_id = h.id')
//            ->join('customer c','s.customer_id = c.id')
//            ->where($where)
//            ->count();
        foreach ($list as &$v){
            $v['status_txt'] = $status[$v['status']];
        }
        $this->success('','',$list);
    }

    public function detail(){
        $ids =input('ids/d',0);
        $model = new checkoutModel();
        $row = $model->find($ids);
        if(empty($ids) || empty($row)){
            $this->error('查无数据');
        }

        $list = Db::name('sales_checkout_goods')
            ->where(array('c.sales_checkout_id'=>$ids))
            ->alias('c')
            ->join('goods g','c.goods_id = g.id','LEFT')
            ->join('supplier_brands b','g.brands_id = b.id','LEFT')
            ->select();
        if(empty($row['contacts']) || empty($row['mobile'])){
            $crow = \app\common\model\customer\Customer::find($row['customer_id']);
            $contacts = $crow['contacts'];
            $mobile = $crow['mobile'];
            $address = $crow['address'];
        }else{
            $contacts = $row['contacts'];
            $mobile = $row['mobile'];
            $address = $row['address'];
        }
        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('contacts',$contacts);
        $this->assign('mobile',$mobile);
        $this->assign('address',$address);
        return $this->view->fetch();
    }
    //发货
    public function deliver(){
        $ids =input('ids/d',0);
        $model = new checkoutModel();
        $row = $model->find($ids);
        if(empty($ids) || empty($row) ){
//        if(empty($ids) || empty($row) || $row['status'] !=2){
            $this->error('查无数据');
        }
        if($this->request->isAjax()){
            $img = input('img');
            $remark = input('remark');
            if(empty($img)){
                $this->error('图片不能为空');
            }
            if(file_exists(dirname(dirname(dirname(dirname(__FILE__)))).'/public'.$img)){
                $data = array(
                    'image'=>$img,
                    'remark'=>$remark,
                    'type'=>7,
                    'source_id'=>$ids,
                );
                //减少库存
                Db::startTrans();
                try {
                    $Slip = new Slip;
                    $ress = $Slip->checkstatus($row['sales_slip_id']);
                    if(!$ress){
                        throw new Exception('异常错误');
                    }

                    $plist = Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$ids))->select();

                    foreach ($plist as $k=>$v){
                        //修改销售单商品状态
                        $sliprow = Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->find();
                        if($sliprow['goods_num'] == $v['goods_num']){ //出库完成
                            Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
                        }else{
                            $num = Db::name('sales_checkout_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id'],'status'=>2))->sum('goods_num');//已经出库的商品数量
                            if($num+$v['goods_num'] == $sliprow['goods_num']){
                                Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
                            }
                        }
                        Db::name('sales_checkout_goods')->where(array('id'=>$v['id']))->update(array('status'=>2));



                        $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                        if($hgood['stock'] == 0){
                            throw new Exception('库存为0');
                        }
                        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                        Db::name('goods_stock_log')->insert(array(
                            'goods_id'=>$v['goods_id'],
                            'createtime'=>time(),
                            'number'=>$row['number'],
                            'type'=>'销售出库单',
                            'source'=>7,
                            'type_id'=>$row['id'],
                            'out_num'=>$v['goods_num'],
                            'before_num'=>$hgood['stock']+$v['goods_num'],
                            'now_num'=>$hgood['stock'],
                            'storehouse_id'=>$row['storehouse_id'],
                            'controller'=>'sales/checkout',
                            'admin_id'=>session('admin')['id'],
                            'group_id'=>$group['group_id'],
                            'company'=>$group['name'],
                            'operator'=>session('admin')['nickname'],
                            'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                            'bill_cost'=>($hgood['balance']/$hgood['stock'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                            'balance'=>$hgood['balance'], //记录的金额当前库存总额
                        ));
                        //减少库存

                        $GoodsHouseStock = new GoodsHouseStock;
                        $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num']);
                        if(!$rr){
                            throw new Exception('库存异常');
                        }
                    }
                    $Voucher = new Voucher;
                    $Voucher->save($data);
                    $model = new checkoutModel();
                    $res = $model->save(array('status'=>3),array('id'=>$ids));
                    if($res){
                        Db::commit();
                        return array(
                            'code'=>1,
                            'msg'=>'发货成功',
                        );
                    }else{
                        throw new Exception('状态异常');
                    }
                }catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }else{
                $this->error('图片路径非法');
            }
//            dump();
            exit;
        }
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }
    //到货
    public function arrive(){
        $ids =input('ids/d',0);
        $model = new checkoutModel();
        $row = $model->find($ids);
        if(empty($ids) || empty($row) || $row['status'] !=3){
            $this->error('查无数据');
        }
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }
}
